package com.yc.cinema.ioc;

import com.yc.cinema.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

public class AnnotationConfigApplicationContext {

    private Class<?> config;
    // IOC容器
    private Map<String, Object> beanMap = new HashMap<>();

    public AnnotationConfigApplicationContext(Class<?> config) {
        this.config = config;

        // 包扫描, 读入所有要管理的bean
        Set<Class<?>> set = scanPackage();

        // 创建对象放入IOC容器
        for (Class<?> c : set) {
            // 读取组件组件(一共4个)
            Component comp = c.getAnnotation(Component.class);
            String id = comp.value();
            if (id.isEmpty()) {
                id = c.getSimpleName(); // 没有id 默认id: 类名+首字母小写
                id = id.substring(0, 1).toLowerCase() + id.substring(1);
            }
            try {
                // 默认 bean 一定有无参数构造方法
                beanMap.put(id, c.newInstance());
            } catch (Exception e) {
                throw new RuntimeException(String.format(
                        "创建%s失败!", c.getName()), e);
            }
        }

        // 自动装配
        for (Object bean : beanMap.values()) {
            // 获取并遍历所有属性
            for (Field f : bean.getClass().getDeclaredFields()) {
                // 判断注解 Autowired (Resource)注解
                if (f.getAnnotation(Autowired.class) != null) {
                    Object property = null;
                    Qualifier q = f.getAnnotation(Qualifier.class);
                    // 如果没有 Qualifier 使用 类对象注入, 有则使用id注入
                    if (q != null) {
                        property = getBean(q.value());
                    } else {
                        property = getBean(f.getType());
                    }
                    // 设置强制访问(非public属性)
                    f.setAccessible(true);
                    // 注入属性值
                    try {
                        f.set(bean, property);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public Object getBean(String id) {
        Object bean = beanMap.get(id);
        if (bean == null) {
            throw new RuntimeException("没有该bean: " + id);
        }
        return bean;
    }

    public <T> T getBean(Class<T> cls) {
        List<Object> list = new ArrayList<>();
        for (Object bean : beanMap.values()) {
            // cls == bean.getClass()
            if (cls.isAssignableFrom(bean.getClass())) {
                list.add(bean);
            }
        }
        if (list.isEmpty()) {
            throw new RuntimeException("没有该bean: " + cls);
        } else if (list.size() > 1) {
            for (Object bean : list) {
                if (bean.getClass().getAnnotation(Primary.class) != null) {
                    return (T) bean;
                }
            }
            throw new RuntimeException("No Querlifer ... " + cls);
        } else {
            return (T) list.get(0);
        }
    }


    /**
     * 包扫描, 读入所有要管理的bean
     *
     * @return
     */
    private Set<Class<?>> scanPackage() {
        /**
         * 作弊: 直接返回 组件类
         */
        Set<Class<?>> set = new HashSet<>();
        set.addAll(Arrays.asList(Cat.class, Dog.class, Person.class));
        return set;
    }
}
